//------------------------------------------------------------------------------
//  <copyright file="GroundTruthLoggerAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  </copyright>
//------------------------------------------------------------------------------

namespace Test.Robotics.Navigation
{
    using System;
    using System.Diagnostics;
    using System.Runtime.Serialization;
    using Microsoft.Robotics.Interaction.Runtime.Input;
    using Microsoft.Robotics.Navigation.Runtime.GroundTruthExtraction;
    using Microsoft.Robotics.Runtime;
    using Microsoft.Robotics.Vision.Runtime.Cameras;
    using Microsoft.Robotics.Vision.Runtime.GroundTruthExtraction;

    /// <summary>
    /// Ground Truth Logger Agent class
    /// This agent generates a ground truth file based on RobotPoseEstimationAgentMessages received.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage(
    "Microsoft.Design",
    "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
    Justification = "PipelineElements clean up resources when OnDeactivated() is called")]
    [DataContract]
    public class GroundTruthLoggerAgent : Agent, ISubscriptionReceiver<GamePadAgentMessage>, ISubscriptionReceiver<RobotPoseEstimationAgentMessage>
    {
        /// <summary>
        /// Path to the output directory
        /// </summary>
        [DataMember(Name = "OutputDir")]
        private readonly string outputDir = default(string);

        /// <summary>
        /// The name of the agent we subscribe to.
        /// </summary>
        [DataMember(Name = "GamePadProducer")]
        private readonly string gamePadProducerName = default(string);

        /// <summary>
        /// The name of the agent we use to update the landmark index.
        /// </summary>
        [DataMember(Name = "CameraPoseProducer")]
        private readonly string cameraPoseProducerName = default(string);
        
        /// <summary>
        /// The name of the agent we subscribe to.
        /// </summary>
        [DataMember(Name = "RobotPoseProducer")]
        private readonly string robotPoseProducerName = default(string);

        /// <summary>
        /// Path to the waypoint file
        /// </summary>
        [DataMember(Name = "WaypointFilePath")]
        private readonly string waypointFilePath = default(string);

        /// <summary>
        /// The GroundTruthLogger 
        /// </summary>
        private GroundTruthLogger groundTruthLogger;

        /// <summary>
        /// The agent we are subscribing to
        /// </summary>
        private IAgentHost gamePadProducerAgent;

        /// <summary>
        /// The agent we are using to update landmark index
        /// </summary>
        private IAgentHost cameraPoseProducerAgent;

        /// <summary>
        /// The agent we are subscribing to
        /// </summary>
        private IAgentHost robotPoseProducerAgent;

        /// <summary>
        /// The previous frame's game buttons
        /// </summary>
        private GamePadAgentMessage.GamePadAgentButtons lastButtons;

        /// <summary>
        /// Camera Pose Estimation Input Forwarder used to pass the UI updates to the camera pose estimation agent.
        /// </summary>
        private IForwarder<CameraPoseEstimationInputMessage> cameraPoseEstimationInputForwarder;

        /// <summary>
        /// Indicates when button has been pressed and we should process the next pose message
        /// </summary>
        private bool waitingForPose;

        /// <summary>
        /// The last landmark ID
        /// </summary>
        private int lastLandmarkId = -1; // initialize to something impossible

        /// <summary>
        /// Initializes a new instance of the <see cref="GroundTruthLoggerAgent"/> class.
        /// </summary>
        /// <param name="name">The name of the agent</param>
        /// <param name="outputDir">The path to the output file</param>
        /// <param name="gamePadProducer">The name of the game pad producer agent</param>
        /// <param name="cameraPoseProducer">The name of the camera pose producer agent</param>
        /// <param name="robotPoseProducer">The name of the robot pose producer agent</param>
        /// <param name="waypointFile">File containing the ids of the landmarks we will visit</param>
        public GroundTruthLoggerAgent(string name, string outputDir, string gamePadProducer, string cameraPoseProducer, string robotPoseProducer, string waypointFile)
            : base(name)
        {
            this.outputDir = outputDir;
            this.gamePadProducerName = gamePadProducer;
            this.cameraPoseProducerName = cameraPoseProducer;
            this.robotPoseProducerName = robotPoseProducer;
            this.waypointFilePath = waypointFile;
        }

        /// <summary>
        /// Initialize the agent
        /// </summary>
        /// <param name="locator">Agent locator to use</param>
        public override void Initialize(AgentLocator locator)
        {
            base.Initialize(locator);

            this.gamePadProducerAgent = locator.GetAgent(this.gamePadProducerName);
            this.gamePadProducerAgent.Subscribe<GamePadAgentMessage>(this);

            this.robotPoseProducerAgent = locator.GetAgent(this.robotPoseProducerName);
            this.robotPoseProducerAgent.Subscribe<RobotPoseEstimationAgentMessage>(this);

            this.cameraPoseProducerAgent = locator.GetAgent(this.cameraPoseProducerName);
            this.cameraPoseEstimationInputForwarder = this.cameraPoseProducerAgent.GetControlPort<CameraPoseEstimationInputMessage>();

            this.groundTruthLogger = new GroundTruthLogger(this.outputDir, this.waypointFilePath);
        }

        /// <summary>
        /// Activate the agent
        /// </summary>
        public override void OnActivated()
        {
            this.gamePadProducerAgent.Activate(); 
            this.cameraPoseProducerAgent.Activate();            
            this.robotPoseProducerAgent.Activate();

            // set the first landmark
            this.cameraPoseEstimationInputForwarder.Post(new CameraPoseEstimationInputMessage(this.groundTruthLogger.CurrentLandmarkId));
            
            base.OnActivated();
        }

        /// <summary>
        /// Deactivate the agent
        /// </summary>
        public override void OnDeactivated()
        {
            this.gamePadProducerAgent.Deactivate();
            this.cameraPoseProducerAgent.Deactivate();
            this.robotPoseProducerAgent.Deactivate();
            
            this.groundTruthLogger.Close();

            base.OnDeactivated();
        }

        /// <summary>
        /// Receive the game pad agent message
        /// </summary>
        /// <param name="padMessage">The message</param>
        public void Receive(GamePadAgentMessage padMessage)
        {
            if (this.lastButtons != null)
            {
                if (padMessage.Buttons.LeftShoulder && (!this.lastButtons.LeftShoulder))
                {
                    Console.WriteLine("Waiting for RobotPose...");
                    this.waitingForPose = true;
                }
            }

            this.lastButtons = padMessage.Buttons;
        }

        /// <summary>
        /// Receive the robot pose agent message
        /// </summary>
        /// <param name="poseMessage">The message</param>
        public void Receive(RobotPoseEstimationAgentMessage poseMessage)
        {
            if (this.waitingForPose)
            {
                if (poseMessage.RobotPose == null || !poseMessage.RobotPose.HasValue)
                {
                    Console.WriteLine("Ground truth marker not visible or pose estimator not properly initialized.  Cancelling capture. Press capture button to try again.");
                    Console.Beep(400, 1000);
                    this.waitingForPose = false;
                    return;
                }

                if (poseMessage.Landmark == null)
                {
                    throw new InvalidOperationException("Null landmark indicates the camera pose estimator was not properly initialized or activated");
                }
                
                if (poseMessage.Landmark.Id != this.lastLandmarkId)
                {
                    // this must be a stale message just ignore it.  Next one should be correct.
                    return;
                }
                else
                {
                    this.waitingForPose = false;

                    if (!this.groundTruthLogger.LogGroundTruthPose(poseMessage.RobotPose.Value, poseMessage.LocalPose.Value))
                    {
                        // no more waypoints to caputre;
                        return;
                    }
                    
                    int currentLandmarkId = this.groundTruthLogger.CurrentLandmarkId;
                    if (currentLandmarkId != this.lastLandmarkId)
                    {
                        this.cameraPoseEstimationInputForwarder.Post(new CameraPoseEstimationInputMessage(currentLandmarkId));
                        this.lastLandmarkId = currentLandmarkId;
                    }
                }

                Console.Beep(800, 200);
            }
        }
    }
}
